<template>
    <view class="order-detail">
        <view class="order-card">
            <view class="order-status">
                <view class="status-wrapper">
                    <text class="status-text">{{ getStatusText(orderInfo.status) }}</text>
                    <view v-if="orderInfo.status === 0" class="countdown">
                        <text>支付剩余时间</text>
                        <text class="time">{{ formatCountdown }}</text>
                    </view>
                </view>
            </view>

            <view class="order-items">
                <view class="order-item" v-for="item in orderInfo.orderItems" :key="item._id">
                    <view class="item-content">
                        <image class="item-image" :src="item.spuImg" mode="aspectFill" />
                        <view class="item-info">
                            <view class="item-name">{{ item.skuName }}</view>
                            <view class="item-specs">{{ formatSpecifications(item.specifications) }}</view>
                            <view class="item-price-qty">
                                <text class="price">￥{{ item.price }}</text>
                                <text class="quantity">x{{ item.quantity }}</text>
                            </view>
                        </view>
                    </view>
                    <view class="w-full flex justify-end">
                        <wd-button custom-class="mt-3" v-if="item.status === 1 || item.status === 2" @click="clickRefund(item.orderNo)" size="small" type="info"
                            >退款</wd-button
                        >
                    </view>
                </view>
            </view>

            <view class="order-summary">
                <view class="summary-item">
                    <text class="label">订单编号</text>
                    <text class="value">{{ orderInfo.orderNo }}</text>
                </view>
                <view class="summary-item">
                    <text class="label">创建时间</text>
                    <text class="value">{{ formatDate(orderInfo.createdAt) }}</text>
                </view>
                <view class="summary-item">
                    <text class="label">商品总数</text>
                    <text class="value">{{ calcTotal(orderInfo.orderItems) }}件</text>
                </view>
                <view class="summary-item total">
                    <text class="label">订单总额</text>
                    <text class="value price">￥{{ calcPrice(orderInfo.orderItems) }}</text>
                </view>
            </view>
        </view>

        <view class="action-buttons">
            <wd-button v-if="orderInfo.status === 0" @click="clickPay" size="small" type="primary">付款</wd-button>
            <wd-button v-if="orderInfo.status === 0" @click="handleCancel" size="small" type="info">取消订单</wd-button>
        </view>

        <PayOrder :onSuccess="() => null" @success="fetchOrderDetail" ref="payOrderRef" :orderNo="orderNo" :orderItems="orderInfo.orderItems" />
        <wd-message-box selector="wd-message-box-slot">
            <wd-textarea v-model="refundReason" placeholder="请输入退款原因" maxlength="200" show-word-limit></wd-textarea>
        </wd-message-box>
        <wd-message-box selector="message" />
    </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import { getOrder, cancelOrder, refundOrder } from "@/api/order";
import { useMessage, useToast } from "wot-design-uni";
import PayOrder from "@/components/PayOrder.vue";
import dayjs from "dayjs";
import { onLoad } from "@dcloudio/uni-app";

const orderInfo = ref({});
const orderNo = ref("");
const refundReason = ref("");
const payOrderRef = ref();
const message = useMessage("message");
const refundMessage = useMessage("wd-message-box-slot");
const toast = useToast();
const countdown = ref(0);
const timer = ref(null);

const formatCountdown = ref("00:00");

let hasTimeout = false;
const fetchOrderDetail = async () => {
    const res = await getOrder(orderNo.value);
    orderInfo.value = res.data;
    if (orderInfo.value.status === 0) {
        const calcCutDown = () => {
            const createTime = new Date(orderInfo.value.createdAt).getTime();
            const now = Date.now();
            let timer;
            if (now - createTime >= 30 * 60 * 1000) {
                formatCountdown.value = "00:00";
                clearInterval(timer);
                if (!hasTimeout) fetchOrderDetail();
                hasTimeout = true;
            } else {
                const diff = 30 * 60 * 1000 - (now - createTime);
                const minutes = Math.floor(diff / 1000 / 60);
                const seconds = Math.floor((diff - minutes * 60 * 1000) / 1000);
                formatCountdown.value = `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
            }
        };
        calcCutDown();
        timer = setInterval(() => {
            calcCutDown();
        }, 1000);
    }
};

// 格式化规格
const formatSpecifications = specifications => {
    let result1 = {};
    specifications.forEach(item => {
        result1 = { ...result1, ...item };
    });
    let result2 = "";
    for (const key in result1) {
        result2 += `${key}:${result1[key]},`;
    }
    return result2.slice(0, result2.length - 1);
};

// 计算商品总数
const calcTotal = orderItems => {
    let total = 0;
    orderItems?.forEach(item => {
        total += item.quantity;
    });
    return total;
};

const calcPrice = orderItems => {
    return orderItems?.reduce((total, item) => total + item.price * item.quantity, 0) || 0;
};

const formatDate = dateStr => {
    return dayjs(dateStr).format("YYYY-MM-DD HH:mm:ss");
};

const getStatusText = status => {
    const statusMap = {
        0: "待支付",
        1: "待发货",
        2: "待收货",
        3: "已完成",
        4: "已取消",
        5: "退款中",
        6: "已退款",
    };
    return statusMap[status] || "未知状态";
};

const clickPay = () => {
    payOrderRef.value.open();
};

const clickRefund = async (orderNo) => {
    await refundMessage.confirm({
        title: "确认退款",
        beforeConfirm: async ({ resolve }) => {
            await refundOrder({
                orderNo,
                refundReason: refundReason.value,
            });
            toast.success("退款成功");
            fetchOrderDetail();
            resolve(true);
        },
    });
};

const handleCancel = async () => {
    await message.confirm("确定取消订单吗?");
    await cancelOrder(orderNo.value);
    toast.success("取消成功");
    fetchOrderDetail();
};

onLoad(e => {
    orderNo.value = e.orderNo;
    fetchOrderDetail();
});
</script>

<style>
.order-detail {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding: 12px;
    padding-bottom: calc(12px + var(--status-bar-height));
    box-sizing: border-box;
}

.order-card {
    background-color: #fff;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.order-status {
    padding-bottom: 20px;
    border-bottom: 1px solid #f5f5f5;
}

.status-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.status-text {
    font-size: 24px;
    font-weight: bold;
    color: #1989fa;
    margin-bottom: 12px;
}

.countdown {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
}

.countdown text {
    font-size: 14px;
    color: #666;
}

.countdown .time {
    font-size: 32px;
    color: #ee0a24;
    font-weight: bold;
    font-family: monospace;
}

.order-items {
    padding: 20px 0 10px;
    border-bottom: 1px solid #f5f5f5;
}

.order-item {
    margin-bottom: 20px;
}

.order-item:last-child {
    margin-bottom: 0;
}

.item-content {
    display: flex;
}

.item-image {
    width: 100px;
    height: 100px;
    flex-shrink: 0;
    border-radius: 8px;
}

.item-info {
    flex: 1;
    margin-left: 16px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.item-name {
    font-size: 16px;
    color: #333;
    font-weight: 500;
}

.item-specs {
    font-size: 14px;
    color: #999;
    margin: 8px 0;
}

.item-price-qty {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.price {
    color: #ee0a24;
    font-weight: bold;
    font-size: 18px;
}

.quantity {
    color: #999;
    font-size: 14px;
}

.order-summary {
    padding-top: 20px;
}

.summary-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
    font-size: 14px;
}

.summary-item.total {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #f5f5f5;
    font-size: 16px;
}

.label {
    color: #666;
}

.value {
    color: #333;
}

.action-buttons {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 12px 20px;
    background-color: #fff;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}
</style>
